package com.safety51.bi.service;

import com.safety51.bi.entity.ChartConfig;
import com.safety51.bi.entity.ChartDataRequest;
import com.safety51.bi.entity.DimensionConfig;
import com.safety51.bi.entity.MetricConfig;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChartDataService {

    private final ChartConfigService chartConfigService;
    private final DataQueryService dataQueryService;
    private final EChartsGenerator echartsGenerator;

    public ChartDataService(ChartConfigService chartConfigService,
                            DataQueryService dataQueryService,
                            EChartsGenerator echartsGenerator) {
        this.chartConfigService = chartConfigService;
        this.dataQueryService = dataQueryService;
        this.echartsGenerator = echartsGenerator;
    }

    public Object getChartData(ChartDataRequest request) {
        ChartConfig config = chartConfigService.getConfigByChartId(request.getChartId());
        List<Map<String, Object>> data = dataQueryService.executeQuery(
                config,
                request.getFilters(),
                request.getPage(),
                request.getPageSize());
        return echartsGenerator.generateOptions(config, data);
    }

    public Object getTableData(ChartDataRequest request) {
        ChartConfig config = chartConfigService.getConfigByChartId(request.getChartId());
        List<Map<String, Object>> data = dataQueryService.executeQuery(
                config,
                request.getFilters(),
                request.getPage(),
                request.getPageSize());
        // 获取总数（用于分页）
        Long total = dataQueryService.getTotalCount(config, request.getFilters());

        // 生成表格数据
        Map<String, Object> tableData = new HashMap<>();
        tableData.put("columns", getTableColumns(config));
        tableData.put("data", data);
        tableData.put("total", total);
        tableData.put("page", request.getPage());
        tableData.put("pageSize", request.getPageSize());
        tableData.put("totalPages", (int) Math.ceil((double) total / request.getPageSize()));
        return tableData;
    }

    // 增强的表格列生成方法
    private List<Map<String, Object>> getTableColumns(ChartConfig config) {
        List<Map<String, Object>> columns = new ArrayList<>();

        // 维度列
        if (config.getDimensions() != null) {
            for (DimensionConfig dim : config.getDimensions()) {
                Map<String, Object> column = new HashMap<>();
                column.put("title", dim.getAlias());
                column.put("dataIndex", dim.getAlias());
                column.put("key", dim.getAlias());
                column.put("width", 120);

                // 根据字段类型设置对齐方式
                if ("date".equals(dim.getField()) || dim.getField().contains("date")) {
                    column.put("align", "center");
                }

                columns.add(column);
            }
        }

        // 指标列
        if (config.getMetrics() != null) {
            for (MetricConfig metric : config.getMetrics()) {
                Map<String, Object> column = new HashMap<>();
                column.put("title", metric.getAlias());
                column.put("dataIndex", metric.getAlias());
                column.put("key", metric.getAlias());
                column.put("width", 120);

                // 数字列右对齐
                if (isNumericMetric(metric)) {
                    column.put("align", "right");
                }

                columns.add(column);
            }
        }

        return columns;
    }

    private boolean isNumericMetric(MetricConfig metric) {
        String expression = metric.getExpression().toUpperCase();
        return expression.contains("SUM(") ||
                expression.contains("COUNT(") ||
                expression.contains("AVG(") ||
                expression.contains("AMOUNT") ||
                expression.contains("PRICE") ||
                expression.contains("TOTAL");
    }
}